const redis = require('redis')
const REDIS_CONF = require('../conf/db')

// 创建客户端 第二个参数是主机或者IP地址
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)

// 监听事件
redisClient.on('error', err => {
    console.log(err);
})

function set(key, val) {
    if (typeof val === 'object') {
        // val 必须是一个字符串
        val = JSON.stringify(val)
    }
    redisClient.set(key, val, redis.print)

}

function get(key) {
    const promise = new Promise((resolve, reject) => {
        redisClient.get(key, (err, val) => {
            if (err) {
                reject(err)
                return
            }
            if (val === null) {
                resolve(null)
            }
            try {
                resolve(JSON.parse(val))
            } catch (ex) {
                resolve(val)
            }
            /*  console.log('val',val);
             //退出
             redisClient.quit() */
        })
    })
    return promise
}

module.exports = {
    set,
    get
}